package com.jx.mlxg.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jx.mlxg.entity.ApprovalNode;
import com.jx.mlxg.entity.ApprovalRecord;
import com.jx.mlxg.mapper.ApprovalNodeMapper;
import com.jx.mlxg.mapper.ApprovalRecordMapper;
import com.jx.mlxg.service.ApprovalFlowService;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;

@Component
public class ApprovalAutoApproveTask {

    @Autowired
    private ApprovalFlowService approvalFlowService;
    @Autowired
    private ApprovalNodeMapper approvalNodeMapper;
    @Autowired
    private ApprovalRecordMapper approvalRecordMapper;

//    @Scheduled(fixedRate = 60000) // 每分钟检查一次
//    public void checkAutoApprove() {
//        // 设置 MDC
//        ThreadContext.put("mdcKey", "suppressLogs");
//        // 获取所有待审批的记录
//        List<ApprovalRecord> pendingRecords = approvalRecordMapper.selectList(new QueryWrapper<ApprovalRecord>()
//                .eq("approve_status", "审批中"));
//
//        for (ApprovalRecord record : pendingRecords) {
//            // 获取节点信息
//            ApprovalNode node = approvalNodeMapper.selectById(record.getNodeId());
//            if (node == null) {
//                continue;
//            }
//
//            // 如果节点设置了自动审批时间
//            if (node.getAutoApproveTime() > 0) {
//                // 计算已等待的时间(分钟)
//                // 优化后的代码
//                long waitingTime = Duration.between(
//                        record.getApproveTime(),                 // 审批时间（LocalDateTime）
//                        LocalDateTime.now()                      // 当前时间（LocalDateTime）
//                ).toMinutes();
//                if (waitingTime >= node.getAutoApproveTime()) {
//                    // 自动通过审批
//                    approvalFlowService.approve(record.getOrderId(), "审批通过", "自动通过",true);
//                }
//            }
//        }
//        // 清除 MDC
//        ThreadContext.remove("mdcKey");
//    }
}